<?php
declare(strict_types=1);

namespace app\api\service\alipay;

use app\common\enum\order\PayType;
use app\common\library\helper;

use app\common\service\BaseService;
use think\facade\Log;
use Yansongda\Pay\Pay;

/**
 *公众号服务类
 */
class Payment extends BaseService
{
    private $config;
    public function __construct(){
        $this->config = config('alipay');
        Pay::config($this->config);
    }

    //支付宝回调
    public function notifyCallback()
    {
        Log::channel('alipay')->info("支付宝异步通知回调处理========");
        try {
            $data = Pay::alipay()->callback(); // 是的，验签就这么简单！
            Log::channel('alipay')->info('===='.$data);
            $res = helper::jsonDecode($data);
            if(isset($res['notify_type']) && $res['notify_type'] == 'trade_status_sync'){
                if($res['trade_status'] == 'TRADE_SUCCESS'){
                    //支付宝支付成功
                    $post_data = [
                        'out_trade_no' => $res['out_trade_no'],
                        'transaction_id' => $res['trade_no']
                    ];
                    (new PaySuccess())->onPaySuccess(PayType::ALIPAY,$post_data);
                }
            }
            return Pay::alipay()->success();
        } catch (\Exception $e) {
            Log::channel('alipay')->info($e->getMessage()."回调出错------");
            return 'false';  //支付宝回调要返回success和false字符串
        }

    }

    //支付宝响应回调
    public function returnCallback(){
        Log::channel('alipay')->info("支付宝响应回调处理========");
        try {
            echo '支付成功';
            return Pay::alipay()->success();
        } catch (\Exception $e) {
            echo '支付失败';
            Log::channel('alipay')->info($e->getMessage()."回调出错------");
            return 'false';  //支付宝回调要返回success和false字符串
        }
    }

    //支付宝转账处理
    public function transfer($postData)
    {
        //todo 接口可能出现超时情况，但实际已经转账成功，在回调处理判断是否转账成功
        try {
            $result = Pay::alipay()->transfer([
                'out_biz_no' => $postData['order_no'] ?? orderNo(),
                'trans_amount' => $postData['amount'] ?? 1,
                'product_code' => 'TRANS_ACCOUNT_NO_PWD',
                'biz_scene' => 'DIRECT_TRANSFER',
                'payee_info' => [
                    'identity' => $postData['identity'] ?? 'msigfl7811@sandbox.com',
                    'identity_type' => 'ALIPAY_LOGON_ID',
                    'name' => $postData['name'] ?? 'msigfl7811'
                ],
            ]);
            //Log::channel('cashout')->info('支付转账接口结果：'.json_encode($result,JSON_UNESCAPED_UNICODE));
            return $result;
        }catch (\Exception $e){
            //Log::channel('cashout')->info('支付转账接口异常：'.$e->getMessage());
            return [
                "sub_msg" => $e->getMessage()
            ];
        }
    }

    //支付宝H5
    public function wap($postData)
    {
        try {
            $result = Pay::alipay()->wap([
                'out_trade_no' => $postData['order_no'] ?? orderNo(),
                'total_amount' => $postData['total_amount'] ?? 1,
                'subject' => '白泽支付',
                'quit_url' => $postData['quit_url'],   //用户付款中途退出返回商户网站的地址
            ]);
            Log::channel('alipay')->info('支付宝H5结果：'.json_encode($result,JSON_UNESCAPED_UNICODE));
            $data = $result->getBody()->getContents();
            return self::SplicingParameters($data);
        }catch (\Exception $e){
            Log::channel('alipay')->info('支付宝H5支付异常：'.$e->getMessage());
            return [
                "sub_msg" => $e->getMessage()
            ];
        }
    }

    //支付宝app
    public function app($postData)
    {
        try {
            $result = Pay::alipay()->app([
                'out_trade_no' => $postData['order_no'] ?? orderNo(),
                'total_amount' => $postData['total_amount'] ?? 1,
                'subject' => '白泽支付',
                'quit_url' => $postData['quit_url'],   //用户付款中途退出返回商户网站的地址
            ]);
            Log::channel('alipay')->info('支付宝app结果：'.json_encode($result,JSON_UNESCAPED_UNICODE));
            $data = $result->getBody()->getContents();
            //dd($data);
            return $data;
        }catch (\Exception $e){
            Log::channel('alipay')->info('支付宝app支付异常：'.$e->getMessage());
            return [
                "sub_msg" => $e->getMessage()
            ];
        }
    }

    /**拼接支付宝跳转链接
     * @param $data
     */
    private static function SplicingParameters($data): string
    {
        preg_match_all("/<input type='hidden' name='(.*?)' value='(.*?)'\/>/ism",$data,$matchs);
        $url = 'https://openapi.alipay.com/gateway.do';
        $name = $matchs[1];
        $value = $matchs[2];
        $merge = array_combine($name,$value);
        ksort($merge);
        return $url.'?'.http_build_query($merge);
    }



}